
#本案例代码只是作为用户的参考代码，稳定性欠缺，所以不建议直接商用项目
import utime as time
import app_server_aliyun
from modem import net
import modem
import app_config
import app_server_mqtt
import app_network
import app_server_tcp
import app_led
import app_relay
import app_adc
from driver import TIMER
from driver import GPIO
import _thread
import app_uart_recv_send
import uos

#把可读写的文件移动到可读写的用户文件夹区域,/luadb目录是只读区域
#系统优先识别/haas目录里的board.json，/haas目录没有board.json，才会读取/luadb目录里的board.json
list_json = uos.listdir("/haas/")
print(list_json)
if ("board.json") not in list_json: 
    uos.rename("/luadb/board.json","/haas/board.json")
if ("cfg.json") not in list_json: 
    uos.rename("/luadb/cfg.json","/haas/cfg.json")

# ai输入电流 4-20ma  ,电压 0-5v
ai_current_max=20
ai_voltage_max=5

count=0
loopFlag=False
uploadInterval=0
def timer_cb(args):
    global count
    global uploadInterval
    global loopFlag
    if count<uploadInterval:
        loopFlag=False
        count+=1
    else:
        count=0
        loopFlag=True  

timer = TIMER(0)
timer.open(period=1000, mode=TIMER.PERIODIC, callback=timer_cb)  


def main():
    global loopFlag,uploadInterval
    time.sleep(3)
    # app_uart_input.start_input_cmd_thread()
    app_led.led_disp_thread()
    result,option=app_config.read_cfg()
    app_uart_recv_send.recv_data(result) 
    app_uart_recv_send.uart_thread() 
      
    
    FwVersion=modem.info.getDevFwVersion()
    uploadInterval=result["uploadInterval"]
    
    # 联网
    ret=app_network.connect_network()
    if ret:
        # option：0:透传模式;1:自定义编程模式-aliyuIot; 2-自定义编程模式-tcp;3-自定义编程模式-mqtt 
        if option==0:
            app_server_aliyun.aliyun_login(result["deviceName"],result["productKey"],result["productSecret"],result["heartBeat"],result["region"])
           
        elif option==1:
            app_server_aliyun.aliyun_login(result["deviceName"],result["productKey"],result["productSecret"],result["heartBeat"],result["region"])
            # 自定义模式下，上报数据
            # 例如：
            # while True:
            #     app_server_aliyun.update("xx","yy")
            #     time.sleep(1)
            pass
        elif option ==2:
            app_server_tcp.tcp_main(result["ip"],result["port"])
            # 自定义模式下，上报数据 
            # 例如：            
            # while True:
            #     app_server_tcp.update({"xx":"yy"})
            #     time.sleep(1)
            pass

        elif option==3:
            app_server_mqtt.mqtt_connect(result["clientId"],result["userName"],result["password"],result["mqttAddr"],result["port"],result["heartBeat"],result["get_topic"],result["post_topic"],result["qos"])
            # 自定义模式下，上报数据
            # 例如：
            # while True:
            #     app_server_mqtt.update("xx","yy")
            #     time.sleep(1)
            pass    
    else:
        print("failed to connect net")
    

    # # 透传模式下
    while True:
        if app_server_aliyun.get_mqtt_connect_flag():
            app_server_aliyun.update("csq",net.getCsq())
            app_server_aliyun.update("name",result["name"])
            app_server_aliyun.update("id",result["id"])
            app_server_aliyun.update("adcType",result["adcType"])
            app_server_aliyun.update("heartBeat",result["heartBeat"])
            app_server_aliyun.update("rs232Config",{"enable":result["rs232"]["enable"],"baudRate":result["rs232"]["baudRate"],"dataWidth":result["rs232"]["dataWidth"],"stopBits":result["rs232"]["stopBits"],"parity":result["rs232"]["parity"]})
            app_server_aliyun.update("rs485Config",{"enable":result["rs485"]["enable"],"baudRate":result["rs485"]["baudRate"],"dataWidth":result["rs485"]["dataWidth"],"stopBits":result["rs485"]["stopBits"],"parity":result["rs485"]["parity"]})
            app_server_aliyun.update("subcontractInterval",result["subcontractInterval"])
            app_server_aliyun.update("configInfo",{"deviceName":result["deviceName"],"productKey":result["productKey"],"productSecret":result["productSecret"],"region":result["heartBeat"]})
            app_server_aliyun.update("relay1",app_relay.get_relay_state(1))      
            app_server_aliyun.update("relay2",app_relay.get_relay_state(2))   
            app_server_aliyun.update("aiMode",{"aiMode1":result["aiMode1"],"aiMode2":result["aiMode2"]})     
            app_server_aliyun.update("diMode",{"diMode1":result["diMode1"],"diMode2":result["diMode2"]})  
            if result["adcType"]==0:
                app_server_aliyun.update("aiData",{"aiData1":app_adc.get_ai_current_value()[0],"aiData2":app_adc.get_ai_current_value()[1]})
            else:
                app_server_aliyun.update("aiData",{"aiData1":app_adc.get_ai_voltage_value()[0],"aiData2":app_adc.get_ai_voltage_value()[1]})
            app_server_aliyun.update("diData",{"diData1":app_adc.get_di_value()[0],"diData2":app_adc.get_di_value()[1]})  
            app_server_aliyun.update("imei",modem.info.getDevImei())
            app_server_aliyun.update("iccid",modem.sim.getIccid())
            app_server_aliyun.update("haasVersion",FwVersion[:FwVersion.find(",")])
            app_server_aliyun.update("appVersion",app_server_aliyun.get_app_version())
            app_server_aliyun.update("uploadInterval",result["uploadInterval"])   
            break
        else:
            print("failed to connect aliyun")
            time.sleep(1)
    a=0
    while True:
        a+=1
        time.sleep_ms(1000)
        print(a)
        print("------------end-----------")


        





if __name__ == '__main__':
    main()




    






